package infolayer2.servlet;

import infolayer2.Minibase;
import infolayer2.graph.Context;
import infolayer2.graph.Graph;
import infolayer2.json.Json;
import infolayer2.mql.MqlProcessor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



@SuppressWarnings("serial")
public class MqlApiServlet extends HttpServlet {
  
  
  
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    
    Graph graph = Minibase.getGraph();

    String path = request.getPathInfo();
    System.out.println("path: " + path + " Query: " + request.getParameter("query"));
    
    Context context = new Context(graph);
    Json jsonRequest = Json.parse(request.getParameter("query"));
    Json jsonQuery = jsonRequest.getJson("query");
    
    MqlProcessor mqlProcessor = new MqlProcessor(context);
    Json jsonResult;
    if ("/mqlread".equals(path)) {
      jsonResult = mqlProcessor.read(jsonQuery);
    } else if ("/mqlwrite".equals(path)) {
      jsonResult = mqlProcessor.write(jsonQuery);
    } else {
      throw new IllegalArgumentException("Unreognized path: " + path);
    }
    
    Json jsonResponse = Json.createObject();
    jsonResponse.setJson("result", jsonResult);

    PrintWriter writer = response.getWriter();
    writer.write(request.getParameter("callback") + "(");
    writer.write(jsonResponse.serialize());
    writer.write(")\n");
    
    System.out.println("Result: " + jsonResult.serialize());
  }
  
  
}
